var express = require('express');
var router = express.Router();
let db = require('../tools/Db');
let to = require('../tools/to');
let md5 = require('md5');
let uuid = require('uuid');
let jwt = require('jsonwebtoken');
let {secret} = require('../tools/config');
let intercept = require('../tools/intercept');
let formidable = require('formidable');
let fs = require('fs');
let path = require('path');
let timeStamp = require('time-stamp');

//用户注册
router.post('/reg',async(req,res,next)=>{
    let {username,password} = req.body;
    //将明文密码再次加密
    let pwd = md5(password,secret);
    //生成一个mid
    let mid = uuid.v1();
    //将账号密码写入数据库
    let sql = "insert into e_member(mid,username,password,createdate) values (?,?,?,?)";
    let [err,result] = await to(db.query(sql,[mid,username,pwd,Date.now()]));
    if(!err){
        if(result.affectedRows){
            res.json({code:200,data:null,msg:'注册成功'});
        }else{
            next('注册失败');
        }
    }else{
        next(err);
    }
})

//用户登录
router.post('/login',async(req,res,next)=>{
    let {username,password} = req.body;
    let pwd = md5(password,secret);
    let sql = "select * from e_member where username=? and password=?";
    let[err,result] = await to(db.query(sql,[username,pwd]))
    if(!err){
        if(result.length > 0){
            //将用户的mid提取出来
            let [{mid}] = result;
            //生成jwt字符串，附加到json中
            let token = jwt.sign({mid:mid,exp:Date.now()+1000*60*60*24},secret);
            res.json({code:200,data:{token,username,mid},msg:'登录成功'});
        }else{
            next('账号或密码错误');
        }
    }else{
        next(err);
    }
})

//添加token的拦截验证
router.use(intercept());

//根据mid获取用户
router.get('/user',async(req,res)=>{
    let {mid} = req.query;
    let sql = "select * from e_member where mid=?";
    let result = await db.query(sql,[mid]);
    res.json({code:200,data:result,msg:'获取用户成功'});
})

//根据mid更新用户
router.put('/user',async(req,res)=>{
    let {brithday,username,sex,city,mid} = req.body;
    let sql = "update e_member set birthdate=?,username=?,sex=?,city=? where mid=?";
    let result = await db.query(sql,[brithday,username,sex,city,mid]);
    if(result.affectedRows > 0){
        res.json({code:200,data:result,msg:'更新用户成功'});
    }else{
        res.json({code:202,data:result,msg:'更新用户失败，请检查参数'});
    }
})

//用户头像上传
router.put('/uploadhead',(req,res)=>{
    // 中间件配置
    const form = formidable({ multiples: true,uploadDir:"./uploads/avatar" });
    // 设置upload为上传文件存放目录，或者写法如下：
    // form.uploadDir="./upload";
    // form.parse() 从请求对象中解析出表单数据
    form.parse(req, (err, fields, files) => {
        let {mid} = fields;
        let imgPath = files.photo.path;
        let fileName = files.photo.name;
        let extName = path.extname(fileName);
        let originName = imgPath + extName;
        fs.rename(imgPath,originName,async(err)=>{
            let sql = "update e_member set head_photo_url=? where mid=?";
            let result = await db.query(sql,[originName,mid]);
            // console.log(result);
            if(result.affectedRows > 0){
                res.json({code:200,data:result,msg:'更新用户成功'});
            }else{
                res.json({code:202,data:result,msg:'头像上传失败，请检查'});
            }
        })
    });
})

//课程报名
router.post('/study',async(req,res)=>{
    let {mid,cid} = req.body;
    //订单号，日期字符串+随机六位数字 组成
    let oid = timeStamp('YYYYMMDDHHmmss') + (Math.random()).toString().substring(2,6);
    console.log(oid);
    //判断：该账号下课程是否已经报名了
    let sql1 = "select * from e_order where mid=? and cid=?";
    let result1 = await db.query(sql1,[mid,cid]);
    if(result1.length > 0){
        res.json({code:200,data:result1,msg:'已经报名了'});
        return;
    }

    let sql2 = "insert into e_order(oid,mid,cid,createdate,status) values(?,?,?,?,1)";
    let result2 = await db.query(sql2,[oid,mid,cid,Date.now()]);
    if(result2.affectedRows > 0){
        res.json({code:200,data:result2,msg:'课程报名成功'});
    }else{
        res.json({code:202,data:result2,msg:'报名失败，请检查'});
    }
})

//查询报名课程
router.get('/order',async(req,res)=>{
    let {mid} = req.query;
    let sql = "SELECT b.id,b.cid,b.title,CONCAT('upload/course/',b.image_src) AS image_src,b.type_name,b.area_name,b.subject_name FROM e_order AS a LEFT JOIN e_course AS b ON b.cid = a.cid WHERE a.mid=?";
    let result = await db.query(sql,[mid]);
    if(result.length){
        res.json({code:200,data:result,msg:'报名课程获取成功'});
    }else{
        res.json({code:202,data:result,msg:'报名失败，请检查'});
    }
})

//根据mid查询报名课程
router.get('/orders',async(req,res)=>{
    let{mid} = req.query;
    let sql = `SELECT b.id,b.cid,b.title,CONCAT('uploads/course/',b.image_src) AS image_src,b.type_name,b.area_name,b.subject_name FROM e_order AS a LEFT JOIN e_course AS b ON b.cid = a.cid WHERE a.mid=?`;
    let result = await db.query(sql,[mid]);
    res.json({code:200,data:result,msg:'课程查询成功'})
})
module.exports = router;